package cn.hunau.bookstore.admin.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hunau.bookstore.pojo.Book;
import cn.hunau.bookstore.pojo.PageResult;
import cn.hunau.bookstore.pojo.ResponseResult;
import cn.hunau.bookstore.service.BookService;
import cn.hunau.bookstore.service.impl.BookServiceImpl;
import cn.hunau.bookstore.utils.JsonUtils;

/**
 * @author HuangBo
 *
 *         2022-01-22 14:47:30
 *
 */

@WebServlet("/admin/book/*")
public class BookManagerController extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpServletMapping servletMapping = request.getHttpServletMapping();
		String matchValue = servletMapping.getMatchValue();

		PrintWriter out = response.getWriter();

		BookService bookService = new BookServiceImpl();

		if ("page.do".equals(matchValue)) {
			String indexMsg = request.getParameter("pageIndex");
			String sizeMsg = request.getParameter("pageSize");
			int pageIndex = Integer.parseInt(indexMsg);
			int pageSize = Integer.parseInt(sizeMsg);
			PageResult<Book> pageResult = bookService.page(pageIndex, pageSize, null);
			ResponseResult result = new ResponseResult(true, pageResult);
			out.println(JsonUtils.objectToJson(result));
		} else if ("newBook.do".equals(matchValue)) {
			String datas = parseRequestPayloadData(request);
			Book book = JsonUtils.jsonToPojo(datas, Book.class); 
			System.out.println(book);
			String result=bookService.setIndexBook(book, 0);
			out.println(result);
		}
	}

	private String parseRequestPayloadData(HttpServletRequest req) {
		StringBuilder sb = new StringBuilder();
		try (BufferedReader reader = req.getReader();) {
			char[] buff = new char[1024];
			int len;
			while ((len = reader.read(buff)) != -1) {
				sb.append(buff, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
}
